package cn.mrcode.smartFramework.test;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by zhuqiang on 2015/10/24 0024.
 */
public class CGlibProxy implements MethodInterceptor {
    private static CGlibProxy cp = new CGlibProxy();
    public static CGlibProxy getInstance(){
        return cp;
    }
    // 获取代理类
    public <T> T getProxy(Class<T> cls){
        return (T)Enhancer.create(cls,this);
    }

    /**
     *
     * @param o 目标类
     * @param method 目标方法
     * @param objects 目标方法参数
     * @param methodProxy 方法代理
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("后置");
        return result;
    }
}

class HelloCg{
    public void say(String msg) {
        System.out.println(msg);
    }
}

class CGlibTest{
    public static void main(String[] args) {
        HelloCg proxy = CGlibProxy.getInstance().getProxy(HelloCg.class);
        proxy.say("cglib 动态代理,支持没有接口的类哦");
    }
}
